from rest_framework import serializers
from .utils import check_save_user_token
from django_redis import get_redis_connection

from users.models import User
from .models import OAuthQQUser


class QQAuthUserSerializer(serializers.Serializer):

    # 定义需要序列化或反序列化的字段
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    # 校验
    def validate(self, data):
        """校验"""

        # 获取openid
        openid_token = data.get('access_token')  # 取出加密的openid
        openid = check_save_user_token(openid_token)  # 把openid还原
        if not openid:
            raise serializers.ValidationError('access_token无效')
        data['openid'] = openid  # 把解密后的openid存入反序列化时的大字典中后续保存时使用



        # 获取redis中短信验证码和用户输入的做判断
        sms_code = data.get('sms_code')  # 获取前端传过来的验证码
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get('sms_%s' % data.get('mobile'))
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('sms_code错误')


        # 用手机号去查询用户
        mobile = data.get('mobile')
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 手机号不存,说明是一个新用户
            pass
        else:
            if not user.check_password(data.get('password')):
                raise serializers.ValidationError('密码不正确')
            else:
                # 把用户直接加入到反序列化的大字典中,以备后用
                data['user'] = user

        return data



    # 重写create方法
    def create(self, validated_data):
        # 从validated_data来获取user,如果能取到,说明当前用户是已存在的(直接和open绑定)
        user = validated_data.get('user')
        if not user:  # 如果用户不存在,就新增一个用户
            user = User.objects.create(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile']
            )

        # openid关联user
        OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )

        return user  # 把user因为后续生成jwt token需要使用

